#include "ConfigHelper.h"
#include "FileHelper.h"
#include "bingwallpaperservice.h"

BingWallpaperService::BingwallpaperService()
{
    this->url = "http://www.bing.com/HPImageArchive.aspx?format=js&idx=%1&n=%2";
    this->httpClient = new HttpClient();
    QObject::connect(httpClient,SIGNAL(GetStringFinished(QString*)),this,SLOT(OnGetWallpaperFinished(QString*)));
}

BingWallpaperService::~BingWallpaperService()
{

}

QList<WallpaperModel*> BingWallpaperService::GetWallpaper()
{
    qDebug()<<"GetWallpaper()";
    HttpClient httpClient;

    QString saveFolder = ConfigHelper::getInstance()->GetSaveFolder();
    if(saveFolder.isEmpty())
    {
        saveFolder = "G:\\";
    }

    qDebug()<<"SaveFolder: "<<saveFolder;
    this->url = this->url.arg("1","1");
    qDebug()<<"Url :"<<this->url;

    QString str = httpClient.GetStringAsync(this->url);

    QList<WallpaperModel *> localDeserialize = JsonHelper::Deserialize(str);
    qDebug()<<localDeserialize.size();

    for(int i =0;i<localDeserialize.size();i++)
    {
        WallpaperModel* paper = ((WallpaperModel*)localDeserialize.at(i));
//        httpClient.DownloadImage(paper->Url,saveFolder+"\\"+paper->Hash+".jpg");
        httpClient.DownloadImage(paper->Url,paper->Hash+".jpg");
        qDebug()<<paper->CopyRight;
        //emit GetWallpaperFinished(localDeserialize);
    }
    return localDeserialize;
}

void BingWallpaperService::GetWallpaperAsync()
{
    httpClient->GetStringAsync(this->url);
}

void BingWallpaperService::OnGetWallpaperFinished(QString str)
{
    QList<WallpaperModel*> papers = JsonHelper::Deserialize(str);
}




